﻿namespace tinfosvr
{
    using Fleck;
    using System;
    using System.Collections.Generic;
    using System.Linq;

    class TrainTimesServer
    {
        private List<WebSocketClient> mAllSockets = new List<WebSocketClient>();
        private WebSocketServer mServer;

        public void dispose()
        {
            if (mServer != null)
            {
                mServer.Dispose();
                mServer = null;
            }
        }

        public void Init()
        {
            FleckLog.Level = LogLevel.Debug;
            mServer = new WebSocketServer("ws://0.0.0.0:9090", true);
            mServer.Start(delegate (IWebSocketConnection socket) {
                socket.OnOpen = delegate {
                    OnWebSocketOpen(socket);
                };
                socket.OnClose = delegate {
                    OnWebSocketClose(socket);
                };
                socket.OnMessage = delegate (string message) {
                    OnWebSocketRecvMsg(socket, message);
                };
                socket.OnBinary = delegate (byte[] bytes) {
                    OnWebSocketRecvBytes(socket, bytes);
                };
            });
        }

        private void OnWebSocketClose(IWebSocketConnection socket)
        {
            object[] objArray1 = new object[] { "websock close:", socket.ConnectionInfo.ClientIpAddress, ":", (int) socket.ConnectionInfo.ClientPort };
            Console.WriteLine(string.Concat((object[]) objArray1));
            List<WebSocketClient> clients = mAllSockets.Where(x => x.getSock().ConnectionInfo.ClientIpAddress.Equals(socket.ConnectionInfo.ClientIpAddress)
    && x.getSock().ConnectionInfo.ClientPort.Equals(socket.ConnectionInfo.ClientPort)).ToList();
            foreach (WebSocketClient client in clients)
            {
                client.OnClose();
                mAllSockets.Remove(client);
            }
        }

        private void OnWebSocketOpen(IWebSocketConnection socket)
        {
            mAllSockets.Add(new WebSocketClient(socket));
            Console.WriteLine("websock conn:" 
                +  socket.ConnectionInfo.ClientIpAddress + ":" 
                + (int)socket.ConnectionInfo.ClientPort);
        }

        private void OnWebSocketRecvBytes(IWebSocketConnection socket, byte[] bytes)
        {
        }

        private void OnWebSocketRecvMsg(IWebSocketConnection socket, string message)
        {
            List<WebSocketClient> clients = mAllSockets.Where(x => x.getSock().ConnectionInfo.ClientIpAddress.Equals(socket.ConnectionInfo.ClientIpAddress)
                && x.getSock().ConnectionInfo.ClientPort.Equals(socket.ConnectionInfo.ClientPort)).ToList();
            foreach(WebSocketClient client in clients)
            {
                client.OnRecvMsg(message);
            }
        }
    }
}

